import { Inject, Service } from "typedi";
import { CollectionUtils } from "@chulei-ui/utils";
import { storeToRefs } from "pinia";
import { esi } from "../index";
import { AuthService } from "../AuthService";
import { UniverseStruct } from "../../sde/entity";
import { useCacheStore } from "../../sde/cache";
import { Asset } from "./entity";

@Service()
export class AssetsService {
  @Inject(() => AuthService)
  private authService!: AuthService;
  async all(playerId: number) {
    const cacheStore = useCacheStore();
    const { universeElementMap } = storeToRefs(cacheStore);
    const token = await this.authService.getAccessTokenFromPlayerId(playerId);
    const role = await this.authService.getRole(playerId);
    const assets: Asset[] = [];
    let page = 0;
    while (true) {
      page = page + 1;
      const items = await esi.assets.list(playerId, page, token);
      if (!items) {
        break;
      }
      const names = await esi.assets.assertNames(
        playerId,
        items.map((item) => item.item_id),
        token
      );
      assets.push(
        ...items.map((item) => {
          const asset = Asset.from(item);
          asset.role = role;
          asset.name = names.get(item.item_id)?.replace(/<.*?>/g, "");
          if (asset.name === "None" || !asset.name) {
            asset.name = undefined;
          }
          asset.type = cacheStore.getType(item.type_id);
          //@ts-ignore
          asset.location = universeElementMap.value[asset.location_id];
          return asset;
        })
      );
    }
    const assetsMap = CollectionUtils.array2Map(assets, (asset) => asset.item_id);
    for (const asset of assets) {
      const parent = assetsMap[asset.location_id];
      if (parent) {
        asset.parent = parent;
        parent.children.push(asset);
      } else {
        if (!asset.location && asset.location_id !== 2004) {
          try {
            const location = universeElementMap.value[asset.location_id];
            if (location) {
              //@ts-ignore
              asset.location = location!;
              continue;
            }
            //@ts-ignore
            asset.location = await esi.universe.structure(asset.location_id, token);
            //@ts-ignore
            universeElementMap.value[asset.location_id] = asset.location!;
          } catch (e) {
            console.error(e);
            const struct = new UniverseStruct();
            struct.structure_id = asset.location_id;
            struct.name = "无法访问";
            universeElementMap.value[asset.location_id] = struct;
          }
          await new Promise((resolve) => setTimeout(resolve, 50));
        }
      }
    }

    return assets.filter((asset) => !asset.parent);
  }
}
